package com.youthburin.base.taglib;

import java.io.IOException;
import java.util.List;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.lang.StringUtils;
import org.apache.taglibs.standard.lang.support.ExpressionEvaluatorManager;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.youthburin.base.domain.Dict;
import com.youthburin.base.services.DictService;

public class DictTag extends TagSupport {
	private static final long serialVersionUID = 1L;
	private final String DEFAULT_PAGE_DICT_PREFIX = "PAGE_DICT_";
	private String model;// 如 rmp 模块，值为rmp
	private String type;// 字典类型
	private String code;// 字典代码

	private boolean showName;// 显示名称

	@Override
	public int doStartTag() throws JspException {
		DictService dictService = getDictService();
		if (dictService != null) {
			if (StringUtils.isNotBlank(type)) {
				String dictAttributeKey = model.toUpperCase() + "_" + DEFAULT_PAGE_DICT_PREFIX + type.toUpperCase();
				if (this.pageContext.getAttribute(dictAttributeKey) == null) {
					List<Dict> dictList = dictService.getByType(type);
					this.pageContext.setAttribute(dictAttributeKey, dictList);
				}
			}

			if (showName) {
				Dict dict = dictService.getByTypeAndCode(type, code);
				try {
					this.pageContext.getOut().write(dict.getName());

					return SKIP_BODY;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return EVAL_PAGE;
	}

	public String getModel() {
		return model;
	}

	public void setModel(String model) {
		this.model = model;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		// 对EL表达式的支持
		try {
			if (code != null)
				this.code = (String) ExpressionEvaluatorManager.evaluate("code", code.toString(), Object.class, this,
						pageContext);
			else
				this.code = null;
		} catch (JspException e) {
			e.printStackTrace();
		}
	}

	public boolean isShowName() {
		return showName;
	}

	public void setShowName(boolean showName) {
		this.showName = showName;
	}

	private DictService getDictService() {
		ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(this.pageContext
				.getServletContext());

		if (StringUtils.equals("rmp", model)) {// rmpDictService
			return (DictService) context.getBean("rmpDictService");
		}

		return null;
	}

}
